#!/bin/bash

trap "echo Goodbye." EXIT

fullname=$0
basename=${0##*/}

if [ "$1" != "-run" -a "$fullname" != "/$basename" ]
then
    cp $fullname /$basename
    exec sh /$basename
fi

t=`uname -r`
osVer=${t%%-*}

if [ "$osVer" = "2.4.1" ]
then
    device="/dev/mtdc4"
elif [ "$osVer" = "2.4.9" ]
then
    device="/dev/mtdc6"
else
    echo "Unknown OS version $osVer"
    exit 1
fi

mount | grep -q " on /xdrive type " ||
{
    echo "Please insert PCMCIA card, then press Enter"
    read

    mount /xdrive ||
    {
        echo "Sorry, I couldn't mount the card"
        exit 1
    }
}

tarfile=/xdrive/upgrade/flash/flash.tar

[ -f $tarfile ] ||
{
    echo "This card doesn't have the flash tar file."
    exit 1
}

killall elgato
killall _siege
killall keepTimeUpdated

if [ -d /flash/egServer/license ]
then
    echo "Saving license file."
    rm /xdrive/elgato.lic
    cp /flash/egServer/license/elgato.lic /xdrive
fi

echo "Unmounting flash file system."
umount /flash ||
{
    echo "Sorry, I couldn't unmount the flash file system"
    exit 1
}

echo
echo "Erasing flash.  This will take 4 minutes or more."
echo

erase $device ||
{
    echo "Error erasing the flash file system."
    echo "This is probably fatal but I'm going to try to continue anyway."
}

echo "Setting date ahead... (don't ask)"
busybox date 010100002010

echo "Mounting flash file system."
mount /flash ||
{
    echo "Could not mount flash file system."
    echo "This is fatal."
    exit 1
}

cd /

echo
echo "Unpacking tar file.  This will take 2 minutes or more."
echo

busybox tar xvf $tarfile

if [ -f /xdrive/elgato.lic ]
then
    echo "Restoring license file."
    cp /xdrive/elgato.lic /flash/egServer/license ||
    {
	echo "Error restoring license file."
	echo "It should still be on the PCMCIA card."
    }
fi

echo "Unmounting PCMCIA card"
umount /xdrive

echo
echo "Please remove the RCMCIA card then press Enter."
read

echo "Rebooting.  If reboot doesn't complete please cycle power"
echo

reboot

